package com.cdtu.sys.service.impl;


import com.cdtu.sys.domain.Role;
import com.cdtu.sys.domain.User;
import com.cdtu.sys.domain.UserVo;
import com.cdtu.sys.mapper.RoleMapper;
import com.cdtu.sys.mapper.UserMapper;
import com.cdtu.sys.service.IUserService;

import com.cdtu.sys.utils.DataGridView;
import com.cdtu.sys.utils.SysConstant;
import com.github.pagehelper.Page;
import com.github.pagehelper.PageHelper;
import org.springframework.stereotype.Service;
import org.springframework.util.DigestUtils;

import javax.annotation.Resource;
import java.util.List;

@Service
public class IUserServiceImpl implements IUserService {

    @Resource
    private UserMapper userMapper;

    @Resource
    private RoleMapper roleMapper;

    @Override
    public User login(UserVo userVo) {
        //密码存入数据库时已经被加密了，查询时，需要先将密码使用md5编码器加密
        String encodedPwd = DigestUtils.md5DigestAsHex(userVo.getPwd().getBytes());
        userVo.setPwd(encodedPwd);
        return userMapper.queryUserByNameAndPwd(userVo);
    }

    @Override
    public DataGridView queryAllUser(UserVo userVo) {
        Page<User> page = PageHelper.startPage(userVo.getPage(), userVo.getLimit());
        List<User> list = userMapper.queryAllUser(userVo);
        return new DataGridView(page.getTotal(),list);
    }

    @Override
    public void addUser(UserVo userVo) {
        //设置用户默认密码，并将默认密码加密
        String encodePwd = DigestUtils.md5DigestAsHex(SysConstant.USER_DEFAULT_PWD.getBytes());
        userVo.setPwd(encodePwd);
        //设置用户类型为普通用户,1=超级管理员，2=不同用户
        userVo.setType(SysConstant.USER_TYPE_NORMAL);

        userMapper.insertUser(userVo);
    }

    @Override
    public void deleteUser(UserVo userVo) {
        userMapper.delUserByUserid(userVo.getUserid());
    }

    @Override
    public void updateUser(UserVo userVo) {
        userMapper.updateUserById(userVo);
    }

    @Override
    public void deleteBatchUser(UserVo userVo) {
        userMapper.delUserAll(userVo);
    }

    @Override
    public void resetUserPwd(UserVo userVo) {
        //内存中修改：设置用户的密码为默认密码
        userVo.setPwd(DigestUtils.md5DigestAsHex(SysConstant.USER_DEFAULT_PWD.getBytes()));
        //保存到到数据库
        userMapper.updateUserById(userVo);
    }

    @Override
    public DataGridView initUserRole(UserVo userVo) {
        Page<Role> page = PageHelper.startPage(userVo.getPage(), userVo.getLimit());
        List<Role> roles = roleMapper.queryAllRole();
        return new DataGridView(page.getTotal(),roles);
    }

    @Override
    public void saveUserRole(UserVo userVo) {
        userVo.setType(SysConstant.USER_TYPE_SUPER);
        userMapper.updateUserById(userVo);
    }

}
